<?php

namespace App\Admin\Controllers;

use App\Store;
use App\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use App\Admin\Actions\Post\UserDetail;

class SettleController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '待结算商户';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User());

        $grid->model()->where('type', 1)->where('merchant_status', 1)->whereNotNull('frozen_date')->orderBy('id', 'desc');

        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->between('frozen_date', '延期日期')->datetime();
            $filter->between('last_login', '登录日期')->datetime();
            $filter->where(function($query){
                $query->where('id', 'like', "%{$this->input}%")->whereOr('phone', 'like', "%{$this->input}%");
            }, '商户ID/联系人电话');

            $filter->where(function($query){
                switch ($this->input) {
                    case '1':
                        $query->whereHas('subsidy', function($query){
                            $query->where('status', 1);
                        });
                        break;
                    case '2':
                        $query->whereDoesntHave('subsidy', function($query){
                            $query->where('status',  1);
                        });
                        break;
                }
            }, '状态')->radio([
                '' => 'All',
                '1' => '已过期',
                '2' => '未过期',
            ]);
        });

        $grid->model()->collection(function(Collection $collection){
            //待结算订单量
            $ordersCount = \DB::table('users_orders')->whereIn('status', [35,40])->groupBy('store_uid')->pluck(\DB::raw('count(*) as count'), 'store_uid');
            $ordersSum = \DB::table('users_orders')->whereIn('status', [35,40])->groupBy('store_uid')->pluck(\DB::raw('sum(settle_amount) as sum'), 'store_uid');
//            过期时间
            $subIng = \DB::table('subsidy')->where('status', 1)->groupBy('uid')->pluck(\DB::raw('count(*)'), 'uid');

            foreach ($collection as $item) {
                $item->orderAmount = (isset($ordersCount[$item->id])?$ordersCount[$item->id]:'0')."/".(isset($ordersSum[$item->id])?$ordersSum[$item->id]:0);
                $item->statusValue = (isset($subIng[$item->id]) ?'在线':'过期');
            }

            return $collection;
        });

        $grid->column('id', '商户ID');
        $grid->column('name', '联系人');
        $grid->column('phone', '联系电话');
        $grid->column('frozen_date', '结算延期日');
        $grid->column('last_login', '最近登录时间');
        $grid->column('orderAmount', '待结算订单/金额');
        $grid->column('statusValue', '任务状态');
        $grid->column('remark', '备注')->editable()->display(function($value){
            return ($this->link_time?$this->link_time.'<br>':''.'<br>').$value;
        });
        $grid->column('storeList', '店铺列表')->display(function ($title) {
            $url = '/admin/user-stores?uid='.$this->id;
            return "<a href='{$url}'>列表</a>";

        });
        $grid->actions(function ($actions) {

            // 去掉删除
            $actions->disableDelete();

            // 去掉编辑
            $actions->disableEdit();
            $actions->disableView();
            $actions->add(new UserDetail());
        });


        
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('uid', __('Uid'));
        $show->field('cate_ids', __('Cate ids'));
        $show->field('title', __('Title'));
        $show->field('imgurl', __('Imgurl'));
        $show->field('lat', __('Lat'));
        $show->field('lnt', __('Lnt'));
        $show->field('address', __('Address'));
        $show->field('address_detail', __('Address detail'));
        $show->field('linkname', __('Linkname'));
        $show->field('phone', __('Phone'));
        $show->field('start_time', __('Start time'));
        $show->field('end_time', __('End time'));
        $show->field('status', __('Status'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        if( request()->input('name') == 'remark' && request()->input('_editable') == 1 ){
            \DB::table('users')->where('id', request()->input('pk'))->update(['link_time'=>date('Y-m-d H:i:s')]);
        }
        $form = new Form(new User());
        $form->text('remark', __('remark'));

        return $form;
    }
}
